package com.n9.qq.android.login.tlv;

import com.n9.qq.util.Util;

/**
 * 数据片段基类
 * @author ice
 * @since 2019/2/11 10:20
 */
public class BaseTlv {
    protected int cmd;
    private int pos;
    private byte[] buf;
    private int headLen;
    private int dataLen;

    public BaseTlv() {
        this.buf = new byte[128];
        this.pos = 0;
        this.headLen = 4;
    }

    private void putCmd(int cmd) {
        Util.int16_to_buf(this.buf, this.pos, cmd);
        this.pos += 2;
        Util.int16_to_buf(this.buf, this.pos, 0);
        this.pos += 2;
    }

    private void putData(byte[] data, int putLen) {
        if (putLen > this.buf.length - this.headLen) {
            expandBuf(putLen);
        }
        System.arraycopy(data, 0, this.buf, this.pos, putLen);
        this.pos += putLen;
        this.dataLen = putLen;
    }

    private void putDataLen() {
        Util.int16_to_buf(this.buf, 2, this.pos - this.headLen);
    }

    private byte[] getBufData() {
        byte[] bufData = new byte[this.pos];
        System.arraycopy(this.buf, 0, bufData, 0, this.pos);
        return bufData;
    }

    protected byte[] getBufData(byte[] data) {
        this.putCmd(this.cmd);
        this.putData(data, data.length);
        this.putDataLen();
        return this.getBufData();
    }



    /**
     * buf扩容
     * @param putLen
     */
    private void expandBuf(int putLen) {
        byte[] newData = new byte[this.headLen + putLen + 64];
        System.arraycopy(buf, 0, newData, 0, this.pos);
        this.buf = newData;
    }

}
